<!-- 注册 -->
<template>

    <div class="register_dialog_popup">

        <div class="register_dialog_content">
            <div class="reg_dia_title">
                <span>{{ t('hall_signUp') }}</span>
                <iconpark-icon class="close" icon-id="exit" color="#fff" size="20px" @click="close"></iconpark-icon>
            </div>
            <nut-form class="reg_dia_form" ref="formRef" :model-value="form" :rules="rules">
                <div class="reg_dia_tabs">
                    <div class="reg_dia_tab" @click="changeTab('account')"
                        :class="{ 'reg_dia_tab_active': formType == 'account' }" v-shrink-on-click>{{
                            t('input_label_account') }}</div>
                    <div class="reg_dia_tab" @click="changeTab('email')"
                        :class="{ 'reg_dia_tab_active': formType == 'email' }" v-shrink-on-click>{{
                            t('input_label_email') }}</div>
                </div>
                <!-- <div class="subtitle" v-if="formType == 'account'">{{ t('input_label_account') }}</div> -->
                <nut-form-item label="" prop="username" class="item" v-if="formType == 'account'">
                    <div class="ipt_box">
                        <nut-input clearable @blur="customBlurValidate(['username'])"
                            @input="customBlurValidate(['username'])" v-model.trim="form.username" class="ipt"
                            type="text" :placeholder="t('input_label_account')">
                        </nut-input>
                    </div>
                </nut-form-item>
                <!-- <div class="subtitle" v-if="formType == 'email'">{{ t('input_label_email') }}</div> -->
                <nut-form-item label="" prop="username" class="item" v-if="formType == 'email'">
                    <div class="ipt_box">
                        <nut-input clearable @blur="customBlurValidate(['username'])"
                            @input="customBlurValidate(['username'])" v-model.trim="form.username" class="ipt"
                            type="text" :placeholder="t('input_label_email')">
                        </nut-input>
                    </div>
                </nut-form-item>
                <!-- <div class="subtitle">{{ t('input_label_password') }}</div> -->
                <nut-form-item label="" prop="password" class="item">
                    <div class="ipt_box">
                        <nut-input clearable @blur="customBlurValidate(['password'])" v-model="form.password"
                            class="ipt" :type="form.showPass == true ? 'text' : 'password'"
                            :placeholder="t('input_label_password')">
                            <template #right>
                                <div class="change_type_wrapper">
                                    <iconpark-icon @click="form.showPass = !form.showPass" v-if="!form.showPass"
                                        name="hide" size="18px"></iconpark-icon>
                                    <iconpark-icon @click="form.showPass = !form.showPass" v-if="form.showPass"
                                        name="show" size="18px"></iconpark-icon>
                                </div>
                            </template>
                        </nut-input>
                    </div>
                </nut-form-item>
                <PasswordLevel v-if="form.password" style="margin-bottom: 6px;position: relative;top:-6px"
                    :password="form.password" />
                <!-- <div class="subtitle">{{ t('input_label_code') }}</div> -->
                <nut-form-item label="" prop="captcha" class="item" v-if="formType == 'account'">
                    <div class="ipt_box">
                        <nut-input clearable @blur="customBlurValidate(['captcha'])" v-model.trim="form.captcha"
                            class="ipt" type="text" :placeholder="t('input_label_code')">
                            <template #right>
                                <div class="code_box" @click="refresh_captcha" style="background-color: #0F0529;">
                                    <ImgT v-shrink-on-click style="width:100%;height:100%;object-fit: contain;"
                                        v-if="captchaURL" :src="captchaURL" alt="captcha" :key="captchaURL" />
                                </div>
                            </template>
                        </nut-input>
                    </div>

                </nut-form-item>
                <nut-form-item label="" prop="captcha" class="item" v-if="formType == 'email'">
                    <div class="ipt_box">
                        <nut-input clearable @blur="customBlurValidate(['captcha'])" v-model.trim="form.captcha"
                            class="ipt" type="text" :placeholder="t('input_label_code')">

                            <template #right>
                                <div :style="{ 'opacity': emailLoading ? '0.5' : 1 }" v-shrink-on-click
                                    class="code_box code_box_btn" @click="onEmailRequest">{{
                                        emailLoadingCount ?
                                            emailLoadingCount : t('get_verification_code2') }}</div>

                            </template>
                        </nut-input>
                    </div>

                </nut-form-item>

                <!-- 邀请码输入框 -->
                <nut-form-item label="" prop="inviteCode" class="item">
                    <div class="ipt_box">
                        <nut-input v-model.trim="form.agent_id" class="ipt" type="number" :placeholder="t('inviteCode')"
                            :readonly="checkURL()" min="0" />
                    </div>
                </nut-form-item>

                <nut-button class="btn_block" :style="{ 'opacity': loading ? '0.5' : 1 }" round block @click="onSubmit">
                    {{ t('btn_label_submit_regist') }}
                </nut-button>


                <div class="link" @click="goLogin">{{ t('btn_label_already_account') }}</div>
            </nut-form>
        </div>

    </div>

</template>

<script setup lang="ts">
import { NetPacket } from "@/netBase/NetPacket";
import { getRandomSign, getDeviceId, aaa, bbb, device_model } from "@/net/Utils";
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { showToast } from '@nutui/nutui'
import PKwebsocket from "@/lolo/Ws";
import pinia from '@/store/index';
import { storeToRefs } from 'pinia';
import { Page } from '@/store/page';
import { User } from '@/store/user';
import { verifyCaptcha, verifyEmail, verifyPassword, verifyAccount } from "@/utils/validateTools";
import '@nutui/nutui/dist/packages/notify/style/css';
import { useI18n } from "vue-i18n";
import { IP } from "@/utils/useStoreMethods";
import PasswordLevel from "./PasswordLevel.vue"

const { t } = useI18n();
const page = Page(pinia);
const { settings } = storeToRefs(page);


const route = useRoute();


const captchaURL = ref(""); // 验证码URl
// const promoURL = ref([]); // 验证码URl
let promoURL: string[] = []; // 普通数组
const handleCaptchaReceive = (captcha: any) => { // 接收验证码图片
    captchaURL.value = "";
    captchaURL.value = captcha.url;
    promoURL = captcha.promotion_url;
};
let codeLoading: any = false
const refresh_captcha = async () => { // 刷新验证码图片
    if (codeLoading) return
    codeLoading = true
    setTimeout(() => {
        codeLoading = false
    }, 1000)
    const req_register_captcha = NetPacket.req_register_captcha();
    const id = await getDeviceId()
    req_register_captcha.sign = getRandomSign(id);
    req_register_captcha.aaa = aaa.toString();
    req_register_captcha.bbb = bbb;
    PKwebsocket.instance.send(req_register_captcha, false, {
        callbackName: 'msg_notify_register_captcha',
        callback: handleCaptchaReceive
    })
};

const emailLoading = ref(false)
const sendEmailed = ref(false)
const onEmailRequest = () => { // 发送邮箱验证码
    if (!(form.value.username)) return showToast.text(t('home_page_enterEmail'))
    if (!verifyEmail(form.value.username)) return showToast.text(t('email_error'))
    if (emailLoadingCount.value || emailLoading.value) return
    const req_get_email = NetPacket.req_get_email_verification_code();
    req_get_email.operate_type = 1;
    req_get_email.email = form.value.username;
    PKwebsocket.instance.send(req_get_email, false, {
        callbackName: 'msg_notify_get_email_verification_code',
        callback: emailVerificationSuccess
    })
    emailLoading.value = true
    sendEmailed.value = true
};

const req_register = NetPacket.req_register_account(); // 注册请求

const get_agent_id_from_url = () => {
    const parsedUrl = new URL(location.href);
    const id = parsedUrl.searchParams.get("id");
    if (!id) {
        return '';
    } else {
        return id
    }
}

// 表单
const formType = ref('account') // account-账号 email-邮箱
const changeTab = (tab: any) => {
    if (formType.value == tab) return
    form.value.username = ''
    form.value.captcha = ''
    form.value.password = ''
    formType.value = tab
    formRef.value?.reset()
}
const form = ref({
    agent_id: get_agent_id_from_url(), // 邀请码
    username: '',
    password: '',
    showPass: false,
    showConfirm: false,
    captcha: ''
})
const checkURL = () => {
    return promoURL.includes(location.origin)
}
const rules = ref({
    username: [
        { required: true, message: t('player_info_tip_1') },
        {
            validator: (val: any) => {
                if (formType.value == 'email' && !verifyEmail(val)) {
                    return Promise.reject(t('account_error'))
                } else if (formType.value == 'account' && !verifyAccount(val)) {
                    return Promise.reject(t('input_tips_account'))
                } else {
                    return Promise.resolve()
                }
            }
        },
    ],
    password: [
        { required: true, message: t('player_info_tip_1') },
        {
            validator: (val: any) => {
                if (!verifyPassword(val)) {
                    return Promise.reject(t('home_page_passwordFormatIncorrect'))
                } else {
                    return Promise.resolve()
                }
            }
        },
    ],
    captcha: [
        { required: true, message: t('empty_tips2') },
        {
            validator: (val: any) => {
                if (formType.value == 'account' && !verifyCaptcha(val)) {
                    return Promise.reject(t('code_error'))
                } else {
                    return Promise.resolve()
                }
            }
        },
    ],
    inviteCode: [
        { required: checkURL(), message: t('input_inviteCode_tips') },
        {
            validator: (val: string) => {
                if (!!val && val.charAt(0) === '0') {
                    return Promise.reject(t('home_page_notCode'))
                } else {
                    return Promise.resolve()
                }
            }
        },
    ],
})
const customBlurValidate = (arr: any) => {
    arr.forEach((key: any) => {
        formRef.value?.validate(key)
    })
}
// 提交前验证
const formRef = ref()
const onSubmit = () => {
    formRef.value?.validate().then((rs: any) => {
        if (rs.valid) {
            if (!form.value.username) return showToast.text(t('account_error'))
            if (formType.value == 'email' && !verifyEmail(form.value.username)) return showToast.text(t('account_error'))
            if (!form.value.password || !verifyPassword(form.value.password)) return showToast.text(t('home_page_passwordFormatIncorrect'))
            if (!form.value.captcha) return showToast.text(t('empty_tips2'))
            if (formType.value == 'account' && !verifyCaptcha(form.value.captcha)) return showToast.text(t('code_error'))
            // 邮箱注册时需要先发验证码
            if (formType.value == 'email' && !sendEmailed.value) return showToast.text(t('home_page_email_code_tip'))
            handleSubmit()
        }
    })

};
const loading = ref(false)
const handleSubmit = async () => {
    if (loading.value) return // 防抖
    loading.value = true
    setTimeout(() => {
        loading.value = false
    }, 1000)

    req_register.username = form.value.username
    req_register.password = form.value.password;
    // req_register.register_type = Local.get('user')?.token !== '' ? 1 : 2
    req_register.register_type = formType.value == 'email' ? 5 : 1
    const id = await getDeviceId()
    req_register.sign = getRandomSign(id);
    req_register.ip = await IP();
    req_register.ip_error = "0";
    req_register.device_model = device_model;
    req_register.channel_id = Number(route.query.channel_id) || 123;
    // @ts-ignore
    req_register.device_id = await getDeviceId();
    req_register.aaa = aaa.toString();
    req_register.bbb = bbb;
    req_register.captcha = form.value.captcha;
    req_register.currency = 1;
    req_register.agent_id = Number(form.value.agent_id) || settings.value.default_agent_id;
    localStorage.setItem('agent_id', req_register.agent_id.toString())
    req_register.from_url = location.origin
    PKwebsocket.instance.send(req_register, false, {
        callbackName: 'msg_notify_register_account',
        callback: registerSuccess
    })
};


// 注册成功
const registerSuccess = async (message: any) => {
    if (message.code == 1) {

        const req_login = NetPacket.req_login();

        req_login.login_type = 2;
        req_login.username = req_register.username;
        req_login.password = req_register.password;
        req_login.device_id = await getDeviceId();
        req_login.device_model = device_model;
        req_login.channel_id = Number(route.query.channel_id) || 123;
        req_login.aaa = aaa.toString();
        req_login.bbb = bbb;
        req_login.ip = await IP();
        req_login.captcha = req_register.captcha;
        PKwebsocket.instance.send(req_login, false, {
            callbackName: 'msg_nodify_login',
            callback: loginSuccess
        })

        setTimeout(() => {
            User(pinia).setReg(false)
        }, 3000)

    } else {
        refresh_captcha()
    }

}

// 登录成功
const loginSuccess = async (message: any) => {
    // showNotify.success(t('home_page_registerSuccess'))

    // localStorage.setItem('readed_notice_ids', '[]')
    // 注册成功 关闭弹窗
    await User(pinia).getUserLoginInfo(message) // 设置登录数据
    setTimeout(() => {
        User(pinia).setReg(false)
    }, 200)
}

// 邮箱验证码获取成功
const emailLoadingCount = ref(0)
let interval: any = null
const loadingEmail = () => {
    emailLoading.value = false
    if (emailLoadingCount.value) return
    if (interval) clearInterval(interval)
    emailLoadingCount.value = 180
    interval = setInterval(() => {
        emailLoadingCount.value--
        if (emailLoadingCount.value <= 0) {
            clearInterval(interval)
        }
    }, 1000)
}
const emailVerificationSuccess = async (message: any) => {

    if (message.code == 1) {
        loadingEmail()
    } else {
        // showNotify.danger(message.message)
    }

    setTimeout(() => {
        emailLoading.value = false
    }, 1000)
}

onMounted(() => {
    refresh_captcha();
})
const close = () => {
    User(pinia).setReg(false)
    setTimeout(() => {
        User(pinia).setRegQuit(true)
    }, 100)
}

const goLogin = () => {
    User(pinia).setReg(false)
    setTimeout(() => {
        User(pinia).setLogin(true)
    }, 200)
}

</script>

<style lang="scss">
.register_dialog_popup {
    .nut-popup {
        background-color: rgba(0, 0, 0, 0);
    }
}


.register_dialog_content {
    div {
        box-sizing: border-box;
    }

    user-select: none;
    overflow: hidden;
    border-radius: 16px;
    background: #131232;
    box-shadow: 0.5px 0.5px 1px 0px #2E296B inset;
    width: 347px;

    .reg_dia_title {

        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        height: 48px;
        border-bottom: 1px solid #242352;
        color: #FFF;
        font-size: 16px;
        font-weight: 500;

        .close {
            font-size: 20px;
            position: absolute;
            right: 20px;
            top: 14px;
        }
    }

    .reg_dia_form {
        padding: 24px 20px 32px 20px;

        .nut-cell-group__wrap {
            box-shadow: none;
            margin: 0 !important;
        }

        .reg_dia_tabs {
            width: 200px;
            border-radius: 8px;
            background: #0B0B23;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px auto;

            .reg_dia_tab {
                flex: 1;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #504F6F;
                font-size: 14px;
                font-weight: 400;
                height: 100%;
            }

            .reg_dia_tab_active {
                border-radius: 8px;
                background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
                box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
                color: #FFF;
                font-weight: 500;
            }
        }

        .subtitle {}

        .btn_block {
            border-radius: 8px;
            background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
            box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
            height: 44px;
            margin-top: 24px;
        }

        .link {
            color: #5D69FF;
            font-size: 12px;
            font-weight: 500;
            line-height: 20px;
            text-decoration: underline;
            text-align: center;
            margin-top: 13px;
        }

        .nut-cell {
            line-height: 48px;
            padding: 0 !important;

            &::after {
                display: none;
            }
        }

        .item {
            margin-bottom: 14px;
            width: 100%;

            &::before {
                display: none !important;
            }

            .nut-form-item__body__slots {
                display: flex;
                align-items: center;
                justify-content: space-between;
                overflow: hidden;
            }

            .nut-form-item__body__tips {
                line-height: 18px;
            }

            .ipt_box {
                flex: 1;
                display: flex;
                align-items: center;
                height: 48px;
                line-height: 48px;
                border-radius: 8px;
                background: #1D1C3C;
                box-shadow: 0.5px 0.5px 1px 0px #333260 inset;
                padding: 0 14px;


                .ipt {
                    flex: 1;
                    // color: #fff;
                    font-size: 14px;
                    font-weight: 500;
                    // background-color: rgba(0, 0, 0, 0);
                    border: none;
                    outline: none;
                    width: 50px;
                }
            }

            .code_box {
                width: 108px;
                height: 44px;
                display: flex;
                justify-content: flex-start;
                align-items: center;
                border-radius: 8px;
                overflow: auto;
                position: relative;
                left: 12px;
                background-color: #0F052A;

                >img {
                    width: 100%;
                    height: 100%;
                }
            }

            .code_box_btn {
                width: 131px;
                height: 44px;
                display: flex;
                justify-content: center;
                align-items: center;
                border-radius: 8px;
                overflow: hidden;
                position: relative;
                left: 12px;
                background: linear-gradient(180deg, #5567FF 0%, #9E1EFF 100%);
                box-shadow: 0.5px 0.5px 1px 0px #9B9EFF inset;
                color: #FFF;
                font-size: 14px;
                font-weight: 500;
            }
        }
    }

    .change_type_wrapper {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 24px;
        color: #8e82c2;
    }
}
</style>